<?php
declare (strict_types=1);

namespace app\common\model;

use ffhome\common\util\CommonUtil;
use ffhome\frame\model\BaseModel;
use think\facade\Db;
use think\helper\Str;

class TourRoute extends BaseModel
{
    const MODEL_NAME = 'tour_route';

    /**
     * 状态:收客中
     */
    const S_PUBLISHING = 1;
    /**
     * 状态:已取消
     */
    const S_CANCELLED = 2;
    /**
     * 状态:已满
     */
    const S_FULLED = 3;
    /**
     * 状态:报名截止
     */
    const S_OVERDUE = 4;

    public static function getById($id)
    {
        $item = Db::name(self::MODEL_NAME)->alias('r')
            ->leftJoin(TourTemplate::MODEL_NAME . ' t', 'r.template_id=t.id')
            ->field('r.id,r.start,r.person_num,r.adult_market_price,r.child_market_price,r.single_price,t.code,t.name,t.days,t.pic')
            ->where('r.id', $id)->limit(1)->select()->toArray();
        if (empty($item)) {
            return [];
        }
        $item = $item[0];
        convertNumber($item);
        self::convert($item);
        return $item;
    }

    public static function convert(&$vo)
    {
        $vo['pic'] = domainUrl($vo['pic']);
        $vo['back'] = date('Y-m-d', strtotime("{$vo['start']} +{$vo['days']} day"));
    }

    public static function get($id)
    {
        $item = Db::name(self::MODEL_NAME)->where('id', $id)->findOrEmpty();
        convertNumber($item);
        return $item;
    }

    public static function getListByTemplateId($templateId)
    {
        $list = Db::name(self::MODEL_NAME)->alias('r')
            ->field('r.id,r.start,r.person_num,r.adult_market_price,r.child_market_price,r.single_price,DATE_FORMAT(r.start,"%Y-%m") _month')
            ->where([['r.template_id', '=', $templateId], ['r.start', '>', date('Y-m-d')], ['r.status', '=', self::S_PUBLISHING]])
            ->order('r.start', 'asc')->select()->toArray();
        foreach ($list as &$vo) {
            convertNumber($vo);
        }
        return $list;
    }

    public static function getInfoByTemplateId($templateId, $days = 0)
    {
        $list = self::getListByTemplateId($templateId);
        $list = CommonUtil::convertToMap($list, '_month');
        $ret = [];
        foreach ($list as $month => $ls) {
            $ret[] = ['month' => $month, 'list' => self::generateMonthList($month, $ls, $days),];
        }
        return $ret;
    }

    private static function generateMonthList($month, $list, $days)
    {
        if ($days > 0) $days--;
        $date = strtotime($month . '-01');
        $week = date('w', $date);
        $montList = [];
        $weekList = [];
        //填充月初空白的内容
        for ($i = 0; $i < $week; $i++) {
            $weekList[] = ['date' => -$i];
        }
        //日期按周填入数组
        $curIndex = 0;
        $count = count($list);
        $current = null;
        if ($curIndex < $count) {
            $current = $list[$curIndex]['start'];
        }
        $date = date('Y-m-d', $date);
        $monthDays = intval(date('d', strtotime($date . ' +1 month -1 day')));
        for ($i = 1; $i <= $monthDays; $i++) {
            $data = ['date' => $i];
            if ($current != null && $current == $date) {
                $data = [
                    'date' => $i,
                    'start' => $current,
                    'back' => date('Y-m-d', strtotime("{$current} +{$days} day")),
                    'id' => $list[$curIndex]['id'],
                    'person_num' => $list[$curIndex]['person_num'],
                    'adult_market_price' => $list[$curIndex]['adult_market_price'],
                    'child_market_price' => $list[$curIndex]['child_market_price'],
                    'single_price' => $list[$curIndex]['single_price'],
                ];
                $curIndex++;
                if ($curIndex < $count) {
                    $current = $list[$curIndex]['start'];
                } else {
                    $current = null;
                }
            }
            $weekList[] = $data;
            $date = date('Y-m-d', strtotime($date . ' +1 day'));
            $week++;
            if ($week == 7) {
                $montList[] = $weekList;
                $week = 0;
                $weekList = [];
            }
        }
        if ($week < 7) {
            $montList[] = $weekList;
        }
        return $montList;
    }
}